package com.example.java.designpattern.prototype;

import com.example.java.designpattern.Divisor;

import java.io.*;

public abstract class CloneDivisor implements Divisor, Cloneable, Serializable {

    @Override
    public Divisor clone() { //object的克隆是浅克隆，且必须实现Cloneable接口
        //下面是深克隆
        ObjectOutputStream oos;
        ObjectInputStream ois;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        try {
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            ois = new ObjectInputStream(bis);
            return (Divisor) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
